package com.zzzy.cont.controller.mycon;

import com.zhuozhengsoft.pageoffice.DocumentOpenType;
import com.zhuozhengsoft.pageoffice.FileMakerCtrl;
import com.zhuozhengsoft.pageoffice.FileSaver;
import com.zhuozhengsoft.pageoffice.word.WordDocumentWriter;
import com.zzzy.common.util.AssertUtil;
import com.zzzy.common.util.FileUtil;
import com.zzzy.common.vo.AjaxResult;
import com.zzzy.common.vo.PageResult;
import com.zzzy.cont.dao.entity.ConActivityNote;
import com.zzzy.cont.dao.entity.Contract;
import com.zzzy.cont.service.ConActivityNoteService;
import com.zzzy.cont.service.mycon.MyConService;
import com.zzzy.cont.vo.contract.ConActivityNoteAddReq;
import com.zzzy.cont.vo.contract.my.*;
import com.zzzy.cont.vo.pageoffice.OpenOfficeFileRes;
import com.zzzy.framework.config.PageofficeConfig;
import com.zzzy.sys.api.UserApi;
import com.zzzy.sys.dto.UserInfoDto;
import com.zzzy.sys.vo.UserSelectPageReq;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * 我的合同
 *
 * @author fc
 * @since 2024-05-27
 */
@Tag(name = "我的合同", description = "con100")
@Validated
@RestController
@RequestMapping("/con/my")
public class MyConController {

    @Resource
    private MyConService myConService;
    @Resource
    private ConActivityNoteService conActivityNoteService;
    @Resource
    protected UserApi userService;
    @Resource
    private PageofficeConfig pageofficeConfig;

    @Operation(summary = "分页列表")
    @GetMapping(value = "/page")
    @PreAuthorize("@pvs.hasPermission('con:my:page')")
    public AjaxResult<PageResult<Contract>> page(@Valid @ParameterObject MyConPageReq queryReq) {
        PageResult<Contract> docPage = myConService.getMyConPage(queryReq);
        return AjaxResult.success(docPage);
    }

    @GetMapping("/getConBasicInfo/{id}")
    @Operation(summary = "获取合同基本信息")
    @Parameter(name = "id", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:page')")
    public AjaxResult<ConBasicInfoRes> getConBasicInfo(@NotNull(message = "合同ID不能为空") @PathVariable("id") Long id) {
        ConBasicInfoRes doc = myConService.getConBasicInfo(id);
        return AjaxResult.success(doc);
    }

    @GetMapping(value = "/getPageOfficeFile/{id}")
    @Operation(summary = "打开文件")
    @Parameter(name = "id", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:page')")
    public AjaxResult<OpenOfficeFileRes> getPageOfficeFile(@NotNull(message = "合同ID不能为空") @PathVariable("id") Long id) {
        String openFileUrl = "/con/my/getConFileStream/" + id;
        OpenOfficeFileRes openOfficeFileRes = myConService.getOpenOfficeResByConId(id, openFileUrl);
        return AjaxResult.success(openOfficeFileRes);
    }

    @GetMapping(value = "/getConFileStream/{id}")
    @Operation(summary = "获取文件流")
    @Parameter(name = "id", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:page')")
    public void getConFileStream(@NotNull(message = "合同ID不能为空") @PathVariable("id") Long id, HttpServletResponse response) {
        ConInfoRes docInfo = myConService.getConInfo(id);
        byte[] fileBlob = Objects.isNull(docInfo.getPdfFileBlob()) ? docInfo.getWordFileBlob() :docInfo.getPdfFileBlob();
        FileUtil.outputFileStream(response, fileBlob, docInfo.getName() + "." + FileUtil.getFileType(fileBlob));
    }

    @GetMapping("/getButton/{id}")
    @Operation(summary = "获取合同可操作按钮")
    @Parameter(name = "id", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:page')")
    public AjaxResult<MyConButtonRes> getButton(@NotNull(message = "合同ID不能为空") @PathVariable("id") Long id) {
        MyConButtonRes buttonRes = myConService.getButton(id);
        return AjaxResult.success(buttonRes);
    }

    @Operation(summary = "活动记录列表")
    @GetMapping(value = "/activityNoteList/{id}")
    @PreAuthorize("@pvs.hasPermission('con:my:page')")
    public AjaxResult<List<ConActivityNote>> activityNoteList(@NotNull(message = "合同ID不能为空") @PathVariable("id") Long id) {
        List<ConActivityNote> activityNoteList = conActivityNoteService.getActivityNoteListByConId(id);
        return AjaxResult.success(activityNoteList);
    }

    @PostMapping("/addActivityNote")
    @Operation(summary = "新增活动记录")
    @PreAuthorize("@pvs.hasPermission('con:my:page')")
    public AjaxResult addActivityNote(@RequestBody @Valid ConActivityNoteAddReq addReq) {
        conActivityNoteService.addUserNote(addReq.getId(), addReq.getContent());
        return AjaxResult.success();
    }

    @Operation(summary = "选择办理人分页列表")
    @GetMapping(value = "/userSelectPage")
    @PreAuthorize("@pvs.hasPermission('con:my:page')")
    public AjaxResult<PageResult<UserInfoDto>> userSelectPage(@Valid @ParameterObject UserSelectPageReq queryReq) {
        PageResult<UserInfoDto> userPage = userService.userSelectPage(queryReq);
        return AjaxResult.success(userPage);
    }

    @PutMapping("/cancel/{id}")
    @Operation(summary = "作废合同")
    @Parameter(name = "id", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:update')")
    public AjaxResult cancel(@NotNull(message = "合同ID不能为空") @PathVariable("id") Long id) {
        myConService.cancel(id);
        return AjaxResult.success();
    }


    @PostMapping("/wordToPdfForMobilePdf/{id}")
    @Operation(summary = "word转换为PDF-留痕")
    @Parameter(name = "id", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:update')")
    public void wordToPdfForMobilePdf(@NotNull(message = "合同ID不能为空") @PathVariable("id") Long id
            , HttpServletRequest request, HttpServletResponse response) throws IOException {
        ConBasicInfoRes conBasicInfo = myConService.getConBasicInfo(id);
        AssertUtil.isEquals(0, conBasicInfo.getRevisionCount(), "仍有修订痕迹无法保存");
        String openFileUrl = "/con/my/getConFileStream/" + id;
        FileMakerCtrl fmCtrl = new FileMakerCtrl(request);
        if (StringUtils.isNotBlank(pageofficeConfig.getWaterMark())) {
            WordDocumentWriter doc = new WordDocumentWriter();
            doc.getWaterMark().setText(pageofficeConfig.getWaterMark());
            fmCtrl.setWriter(doc);
        }
        fmCtrl.fillDocumentAsPDF(openFileUrl, DocumentOpenType.Word, conBasicInfo.getName()+ ".pdf");
        response.getOutputStream().print(fmCtrl.getHtml());
    }

    @PostMapping(value = "/savePdfForMobilePdf/{id}")
    @Operation(summary = "保存pdf-留痕")
    @Parameter(name = "id", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:update')")
    public void savePdfForMobilePdf(@NotNull(message = "合同ID不能为空") @PathVariable("id") Long id,
                                 HttpServletRequest request, HttpServletResponse response) {
        FileSaver fs = new FileSaver(request, response);
        byte[] byteArray = FileUtil.toByteArray(fs.getFileStream());
        myConService.saveMobilePdfBlob(id, byteArray);
        fs.setCustomSaveResult("ok");
        fs.close();
    }

    @Operation(summary = "统计信息")
    @GetMapping(value = "/getStatistics")
    @PreAuthorize("@pvs.hasPermission('con:my:page')")
    public AjaxResult<MyConStatisticsRes> getStatistics() {
        MyConStatisticsRes statistics = myConService.getStatistics();
        return AjaxResult.success(statistics);
    }
}
